package com.keepers.repair.net;

import java.util.HashMap;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;

/**
 * auth aboom
 * date 2018/10/21
 */
public class DataServiceProvider {

    private static DataServiceProvider sDataServiceProvider;

    private HashMap<String, Object> dataServiceMap;

    private Retrofit retrofit;


    public static DataServiceProvider getInstance() {
        if (sDataServiceProvider == null) {
            synchronized (DataServiceProvider.class) {
                if (sDataServiceProvider == null) {
                    sDataServiceProvider = new DataServiceProvider();
                }
            }

        }
        return sDataServiceProvider;
    }

    private Retrofit getRetrofit() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(HttpUtil.getUrlStart())
                    .client(AsyncOkHttpClient.getOkHttpClient())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(SimpleXmlConverterFactory.create())
                    .build();
        }
        return retrofit;
    }

    @SuppressWarnings("unchecked")
    public <T> T provide(Class<T> tClass) {
        if (dataServiceMap == null) {
            dataServiceMap = new HashMap<>();
        }
        if (!dataServiceMap.containsKey(tClass.getName()) || dataServiceMap.get(tClass.getName()) == null) {
            dataServiceMap.put(tClass.getName(), getRetrofit().create(tClass));
        }
        return (T) dataServiceMap.get(tClass.getName());
    }

    /**
     * 切换环境的时候,重新初始化retrofit
     */
    public DataServiceProvider reloadService(String address) {
        if (dataServiceMap == null) {
            dataServiceMap = new HashMap<>();
        }
        dataServiceMap.clear();
        retrofit = new Retrofit.Builder()
                .baseUrl(address)
                .client(AsyncOkHttpClient.getOkHttpClient())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(SimpleXmlConverterFactory.create())
                .build();
        return this;
    }
}
